package com.example.demo.service;

import com.example.demo.common.status.UserStatus;
import com.example.demo.common.util.IdUtils;
import com.example.demo.mapper.UserDynamicSqlSupport;
import com.example.demo.mapper.UserMapper;
import com.example.demo.mapper.UserRoleMapper;
import com.example.demo.model.User;
import com.example.demo.model.UserRole;
import org.mybatis.dynamic.sql.render.RenderingStrategies;
import org.mybatis.dynamic.sql.select.render.SelectStatementProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static org.mybatis.dynamic.sql.SqlBuilder.*;

@Service
public class UserService {

    private UserMapper userMapper;

    private UserRoleMapper userRoleMapper;

    @Autowired
    public void setUserRoleMapper(UserRoleMapper userRoleMapper){
        this.userRoleMapper = userRoleMapper;
    }

    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    public User selectUserByUserName(String phone) {
        SelectStatementProvider selectStatementProvider = select(UserMapper.selectList)
                .from(UserDynamicSqlSupport.user)
                .where(UserDynamicSqlSupport.phone,isEqualTo(phone))
                .build().render(RenderingStrategies.MYBATIS3);
        if (userMapper.selectMany(selectStatementProvider).size() == 0){
            return null;
        }
        return userMapper.selectMany(selectStatementProvider).get(0);
    }

    public User register(String phone, String password) {
        User user = new User();
        String uuid = IdUtils.randomUUID();
        user.setId(uuid);
        user.setPhone(phone);
        user.setPassword(password);
        user.setNickName("未认证信息");
        user.setState(UserStatus.OK.getCode());
        userMapper.insertSelective(user);
        UserRole userRole = new UserRole();
        userRole.setRoleid(1L);
        userRole.setUserid(uuid);
        userRole.setState("1");
        userRoleMapper.insertSelective(userRole);
        return user;
    }

    public void updateUserInfo(User user) {
        userMapper.updateByPrimaryKeySelective(user);
    }

    public void updatePwd(User user) {
        userMapper.updateByPrimaryKey(user);
    }
}
